package com.example.stock.entity.dao;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.stock.comm.Cons;
import com.example.stock.comm.FreqEnum;
import com.example.stock.entity.eo.ProBarStockEo;
import com.example.stock.entity.mapper.ProBarStockMapper;
import com.example.stock.vo.DataVo;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ProBarStockDao extends ServiceImpl<ProBarStockMapper, ProBarStockEo> {

    private List<ProBarStockEo> listData(List<String> tsCodes, LocalDateTime startTime, LocalDateTime endTime) {
        return super.list(Wrappers.<ProBarStockEo>lambdaQuery()
                .in(ProBarStockEo::getTsCode, tsCodes)
                .gt(ProBarStockEo::getTradeTime, startTime)
                .lt(ProBarStockEo::getTradeTime, endTime)
        );
    }

    private Map<String, List<ProBarStockEo>> mapData(List<String> tsCodes, LocalDateTime startTime, LocalDateTime endTime) {
        return this.listData(tsCodes, startTime, endTime).stream().collect(Collectors.groupingBy(ProBarStockEo::getTsCode));
    }

    public Map<String, List<DataVo>> mapDataVo30(List<String> tsCodes, LocalDateTime startTime, LocalDateTime endTime) {
        return this.listData(tsCodes,startTime,endTime).stream()
                .map(t->new DataVo().setTsCode(t.getTsCode()).setTradeTime(t.getTradeTime()).setPrice(t.getClose()))
                .filter(t -> Cons.time60Min.contains(t.getTradeTime().format(Cons.formatHHmm)))
                .collect(Collectors.groupingBy(DataVo::getTsCode));
    }

    public List<DataVo> getRowDataWithFreq(String tsCode,List<String> tsCodes, LocalDateTime startTime, LocalDateTime endTime, FreqEnum freqEnum) {
        List<ProBarStockEo> list = list(
                Wrappers.<ProBarStockEo>lambdaQuery()
                        .eq(StrUtil.isNotBlank(tsCode), ProBarStockEo::getTsCode, tsCode)
                        .in(CollectionUtil.isNotEmpty(tsCodes),ProBarStockEo::getTsCode,tsCodes)
                        .gt(ProBarStockEo::getTradeTime,startTime)
                        .le(ProBarStockEo::getTradeTime,endTime)
                        .orderByAsc(ProBarStockEo::getTradeTime)
        );
        return list.stream()
                .filter(t -> freqEnum == FreqEnum.MIN1 ? true : freqEnum.listTime().contains(t.getTradeTime().format(Cons.formatHHmm)))
                .map(t->new DataVo().setPrice(t.getClose()).setTradeTime(t.getTradeTime()).setTsCode(t.getTsCode()))
                .collect(Collectors.toList());
    }

    public List<String> listAllTsCode() {
        return getBaseMapper().listTsCode();

    }


}
